#include "widget.h"
#include "./ui_widget.h"
#include <QVariant>
#include <LibFT4222.h>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->btnRefresh,&QPushButton::clicked,this,&Widget::RefeshDevice);
    connect(ui->btnOpenCLose,&QPushButton::clicked,this,&Widget::OpenOrCLose);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::RefeshDevice()
{
    DWORD numOfDevices = 0;
    FT_STATUS ftStatus = FT_CreateDeviceInfoList(&numOfDevices);
    if(ftStatus != FT_OK) return;
    for(DWORD iDev=0; iDev<numOfDevices; ++iDev)
    {
        FT_DEVICE_LIST_INFO_NODE devInfo;
        memset(&devInfo, 0, sizeof(devInfo));

        ftStatus = FT_GetDeviceInfoDetail(iDev, &devInfo.Flags, &devInfo.Type, &devInfo.ID, &devInfo.LocId,
                                          devInfo.SerialNumber,
                                          devInfo.Description,
                                          &devInfo.ftHandle);

        if (FT_OK == ftStatus){
            const std::string desc = devInfo.Description;
            if(desc == "FT4222 A")
            {
                ui->comboDeviceList->addItem(QString("I2C(0x%1)").arg(devInfo.LocId),QVariant((uint)devInfo.LocId));
            }
        }
    }

    if(ui->comboDeviceList->count() > 0){
        ui->comboDeviceList->setCurrentIndex(0);
    }
}

void Widget::OpenOrCLose()
{
    bool result;
    if(FT_OpenEx(reinterpret_cast<PVOID>(ui->comboDeviceList->currentData().toUInt()), FT_OPEN_BY_LOCATION, &ft) == FT_OK &&
        FT4222_SetClock(ft, FT4222_ClockRate::SYS_CLK_60) == FT4222_STATUS::FT4222_OK){
        result = FT4222_SPIMaster_Init(ft,FT4222_SPIMode::SPI_IO_SINGLE,FT4222_SPIClock::CLK_DIV_64,FT4222_SPICPOL::CLK_IDLE_LOW,FT4222_SPICPHA::CLK_LEADING,0x01) == FT4222_STATUS::FT4222_OK;
    }
    if(result){
        qDebug()<<"Spi OK";
    }else{
        qDebug()<<"Spi fail";
    }
}
